<?php
require_once "../includes/common.php";
header('Content-Type: application/json');

function generateName($extension) {
    return generatePicId() . '.' . $extension;
}

$allowedExtensions = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'mp4'];
$targetDir = dirname(__DIR__) . '/data/'; // 当前文件上一级目录的 datasss 文件夹
$maxFileSize = 50 * 1024 * 1024; // 50MB

if (isset($_FILES['file'])) {
    $file = $_FILES['file'];

    if ($file['size'] > $maxFileSize) {
        echo json_encode(['status' => '201', 'message' => '文件大小不得超过 50MB']);
        exit;
    }

    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (in_array($extension, $allowedExtensions)) {
        // 确定上传目录
        $subDir = isset($_POST['avatar']) && $_POST['avatar'] == 1 ? 'avatar/' : '';
        $uploadDir = $targetDir . $subDir;

        // 检查并创建目录
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0777, true)) {
                echo json_encode(['status' => '201', 'message' => '目录创建失败error']);
                exit;
            }
        }
        if ($subDir !== 'avatar/') {
            $dateDir = date('Ymd');
            $dateUploadDir = $uploadDir . $dateDir . '/';
            if (!is_dir($dateUploadDir)) {
                if (!mkdir($dateUploadDir, 0777, true)) {
                    echo json_encode(['status' => '201', 'message' => '日期目录创建失败']);
                    exit;
                }
            }
            $targetFile = $dateUploadDir . generateName($extension);
        } else {
            $targetFile = $uploadDir . generateName($extension);
        }

        $newFileName = generateName($extension);
        $targetFile = $uploadDir . ($subDir === 'avatar/' ? $newFileName : date('Ymd') . '/' . $newFileName);

        if (move_uploaded_file($file['tmp_name'], $targetFile)) {
            // 输出绝对路径
            //$absolutePath = realpath($targetFile);
            //echo json_encode(['status' => '200', 'message' => $absolutePath]);
            // 返回相对路径
            // 返回相对路径
            $relativePath = str_replace(dirname(__DIR__), '', $targetFile);
            //$relativePath = '/data/' . $subDir . ($subDir === 'avatar/' ? $newFileName : date('Ymd') . '/' . $newFileName);
            echo json_encode(['status' => '200', 'message' => $relativePath]);
        } else {
            echo json_encode(['status' => '201', 'message' => '文件上传失败']);
        }
    } else {
        echo json_encode(['status' => '201', 'message' => '无效文件类型']);
    }
} else {
    echo json_encode(['status' => '201', 'message' => '无文件上传']);
}
?>
